<?php
/**
 * @Author: lianlianzan(13040@qq.com)
 * @Date:   2018-08-18 16:40:16
 * @Last Modified by:   lianlianzan
 * @Last Modified time: 2020-11-07 12:44:50
 */

namespace app\admin\controller;
use app\common\controller\Backend;

class YoukuToken extends Backend {

	function initialize() {
		parent::initialize();
		$this->saveAndGetConfigIdentify('', '优酷token管理', '', 'youkuToken');

		$this->youkuTokenDao = model('common/YoukuToken');
	}

	public function index() {
		$info = $this->youkuTokenDao->getInfo(1);
		$this->assign('info', $info);

		return $this->fetch();
	}

	public function doSave() {
		$data = input('post.data/a', '', 'pwEscape');

		$result = $this->youkuTokenDao->baseUpdateData(1, $data);
		if ($result !== false) {
			$this->success('保存成功', '');
		} else {
			$this->error('保存失败'.showDbError($this->youkuTokenDao));
		}
	}

	/**
	 * @Author   Zhaojun
	 * @DateTime 2018-09-28
	 * @return   [type]     [description]
	 * http://www2.kszhuangxiu.com/admin/youku/authorize
	 */
	public function authorize() {
		/*****YoukuUpload SDK*****/
		header('Content-type: text/html; charset=utf-8');
		require_once EXTEND_PATH.'YoukuUploadSDK/include/YoukuUploader.class.php';

		$client_id = "731c366ac44137ea"; // Youku OpenAPI client_id
		$client_secret = "31c9422b57cdeed149a270aadf80d59f"; //Youku OpenAPI client_secret

		//$params['access_token'] = "";
		//$params['refresh_token'] = "";
		//$params['username'] = ""; //Youku username or email
		//$params['password'] = md5(""); //Youku password

		$callback = 'http://'.$_SERVER['HTTP_HOST'].'/youku/index/authorize';

		set_time_limit(0);
		ini_set('memory_limit', '128M');
		$youkuUploader = new \YoukuUploader($client_id, $client_secret);
		//print_r($youkuUploader);exit;

		//获取openid
		$json = $youkuUploader->getOauthAccessToken($callback);
		//$openid = $json['openid'];
		$user_access_token = $json->access_token;
		print_r($json);

		if (empty($user_access_token)) {
			$url = $youkuUploader->getOauthRedirect($callback, 'xyz');
			header("Location:".$url);exit;
		}

		$YoukuDao = H::loadmodel('Youku');
		//$youkuInfo = $YoukuDao->get(1);

		$refreshInfo = json_encode($json);
		$data = array(
			'refresh_info'	=> $refreshInfo,
		);
		$YoukuDao->update(1, $data);

	// 	$data = array(
	// 		'access_token'	=> $user_access_token,
	// 	);
	// 	$YoukuDao->update(1, $data);

		header('Content-type: text/html; charset=gbk');
		showmsg("access_token更新成功");
	}

}